#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 2e5 + 5;

int n, m;
string goal = "123804765";
int gx[] = {-1, 0, 0, 0, 1, 2, 2, 2, 1};
int gy[] = {-1, 0, 1, 2, 2, 2, 1, 0, 0};
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int f(string s) {
  int res = 0;
  rep(i, 0, 8) {
    int x = i / 3, y = i % 3;
    int d = s[i] - '0';
    if (d) res += abs(x - gx[d]) + abs(y - gy[d]);
  }
  return res;
}
struct Node {
  int h;
  string s;
  bool operator<(Node o) const { return h > o.h; }
};
int astar(string s) {
  priority_queue<Node> pq;
  unordered_map<string, int> dis;
  pq.push(Node{f(s), s});
  dis[s] = 0;
  while (pq.size()) {
    Node now = pq.top();
    pq.pop();
    string s = now.s;
    if (s == goal) return dis[goal];
    int pos = s.find('0');
    int x = pos / 3, y = pos % 3;
    rep(i, 0, 3) {
      string t = s;
      int xx = x + dx[i], yy = y + dy[i];
      if (xx < 0 || xx > 2 || yy < 0 || yy > 2) continue;
      int pos2 = xx * 3 + yy;
      swap(t[pos], t[pos2]);
      if (!dis.count(t)) {
        dis[t] = dis[s] + 1;
        pq.push(Node{dis[t] + f(t), t});
      }
    }
  }
  return -1;
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  string s;
  cin >> s;
  cout << astar(s);
  return 0;
}